#include <QImage>
#include <QPainter>
#include <QApplication>
#include <QDesktopWidget>
#include <iostream>

#include <PopupOSAL.hpp>
#include "PopupImage.hpp"
#include "PopupImageViewer.hpp"
#include "PopupSettings.hpp"

using namespace std;
using namespace PopupUtils;

PopupImageViewer::PopupImageViewer()
  : QDialog(), m_current(0)
{
  this->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint);
#if QT_VERSION >= 0x040500
  this->setAttribute(Qt::WA_TranslucentBackground, true);
#endif
  connect(&timer, SIGNAL(timeout()), this, SLOT(animate()));
}
//----------------------------------------------------------

PopupImageViewer::~PopupImageViewer()
{
  mutex.lock();
  if (m_current != 0) {
    delete m_current;
  }
  mutex.unlock();
}
//----------------------------------------------------------

void PopupImageViewer::slot_showImage(const QString & p_image,
                                      const QString & p_sender,
                                      bool p_forceFullscreen)
{
  PopupImage *_img = new PopupImage(this, p_image, p_sender, p_forceFullscreen);

  if (_img->isNull())
  {
    delete _img;
  }
  else
  {
    mutex.lock();
    // Image viewer is busy => queue image
    if (m_current != 0)
    {
      m_imageQueue.push(_img);
      mutex.unlock();
    }
    else
    {
      m_current = _img;
      mutex.unlock();
      showImage();
    }
  }
}
//----------------------------------------------------------

void PopupImageViewer::animate()
{
  bool _continue = false;
  QRect _rect(0,0,0,0);

  timer.stop();

  mutex.lock();

  if (m_current != 0)
  {
    // applyFx method will return true only if at least one effect needs
    // some more time to finish
    _continue = m_current->applyFx();
    _rect = QRect(m_current->currentX,
                  m_current->currentY,
                  m_current->currentImageWidth,
                  m_current->currentImageHeight);
  }

  mutex.unlock();

  setGeometry(_rect);
  if (_continue) timer.start(10);
}
//----------------------------------------------------------

bool PopupImageViewer::showImage()
{
  setGeometry(m_current->currentX,
              m_current->currentY,
              m_current->currentImageWidth,
              m_current->currentImageHeight);

  setVisible(true);

  if (m_current->hasDynamicEffects())
  {
    timer.start(1);
  }
  
  return true;
}
//----------------------------------------------------------

void PopupImageViewer::paintEvent(QPaintEvent *)
{
  QPainter _qpainter(this);
  m_current->paint(_qpainter);
}

//----------------------------------------------------------

void PopupImageViewer::mousePressEvent(QMouseEvent*)
{
  this->hide();
  next();
}

void PopupImageViewer::next()
{
  mutex.lock();

  delete(m_current);
  m_current = 0;

  // Get next image from queue
  if (m_imageQueue.size() > 0) {

    m_current = m_imageQueue.front();
    m_imageQueue.pop();
    mutex.unlock();

    showImage();
  }
  else {
    mutex.unlock();
  }
}
